package com.example.springboot;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

@SpringBootApplication
public class SpringbootApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringbootApplication.class, args);
	}
	@RestController
	public class SimpleGetController {

		@GetMapping("/get")
		public ResponseEntity<String> handleGetRequest() {
			// 返回数据
			return ResponseEntity.ok("Hello, this is a GET response!");
		}
	}
	@RestController
	public class SimpleGetController2 {

		@PostMapping("/post")
		public ResponseEntity<String> handlePostRequest(@RequestBody String data) {
			// 处理接收到的数据
			System.out.println("Received data: " + data);
			return ResponseEntity.ok("Data received successfully: " + data);
		}
	}
	// 存储到本地的路径
	private Path uploadDir = Paths.get("D:\\ky_share");
	@RestController
	public class ImageUploadController {
		@PostMapping("/upload/image")
		public ResponseEntity<String> uploadImage(
				@RequestParam("file") MultipartFile image,
				HttpServletRequest request
		) throws IOException {
			System.out.println(uploadDir);
			System.out.println(image.getOriginalFilename());
			Files.createDirectories(uploadDir);
			Files.copy(image.getInputStream(), uploadDir.resolve(image.getOriginalFilename()), StandardCopyOption.REPLACE_EXISTING);
			return ResponseEntity.ok("Image uploaded successfully: " + image.getOriginalFilename());
		}
	}

	@RestController
	public class ImageUploadControllers {
		@GetMapping("/mg/{imageName}")
		public ResponseEntity<FileSystemResource> getImageS(@PathVariable String imageName) {
			System.out.println("D:\\key_share\\" + imageName);
			File imageFile = new File("D:\\key_share\\" + imageName);

			if (imageFile.exists()) {
				HttpHeaders headers = new HttpHeaders();
				headers.add("Content-Type", "image/png"); // 根据图片格式调整
				return new ResponseEntity<>(new FileSystemResource(imageFile), headers, HttpStatus.OK);
			} else {
				System.out.println("图片不存在");
				return new ResponseEntity<>(HttpStatus.NOT_FOUND);
			}
		}
	}

}

